const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const db = require('./db/dbmanager')
const discovery= require('./routes/discovery')
const users = require('./routes/users')
const login=require('./routes/login')
const recommend = require("./routes/recommend");
const index = require('./routes/index')
const uploaded =require('./routes/uploaded')
const edit=require('./routes/edit')
const feedback =require('./routes/feedback')
const mycomment=require('./routes/mycomment')
// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text'],
  multipart:true

}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

//sql
app.use(async (ctx,next)=>{
  ctx.db = db
  await next()
  // console.log(ctx)
})

// routes
app.use(discovery.routes(), discovery.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(login.routes(),login.allowedMethods())
app.use(recommend.routes(), recommend.allowedMethods());
app.use(index.routes(),index.allowedMethods());
app.use(uploaded.routes(),uploaded.allowedMethods());
app.use(edit.routes(),edit.allowedMethods());
app.use(feedback.routes(),feedback.allowedMethods());
app.use(mycomment.routes(),mycomment.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
